package com.example.myapplication.module1.activity

import android.os.Bundle
import android.view.View
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.TimePickerView
import com.example.myapplication.ConstantsData
import com.example.myapplication.R
import com.example.myapplication.databinding.ActivityPlanVisitBinding
import com.example.myapplication.entity.PlanBean
import com.example.myapplication.module1.adapter.PlanListAdapter
import com.example.myapplication.module1.presenter.PlanVisitPresenter
import com.example.myapplication.soaprequest.SoapEnvelop
import com.example.myapplication.soaprequest.request.GetPlanRequest
import com.example.myapplication.soaprequest.request.SoapRequestBody
import com.example.myapplication.widget.CustomerToolbar
import com.example.mylibrary.adapter.BaseRecyclerAdapter
import com.example.mylibrary.base.BaseMvpActivity
import com.example.mylibrary.utils.GsonUtil
import com.example.mylibrary.utils.UiTools
import com.google.gson.reflect.TypeToken
import com.lxj.xpopup.impl.LoadingPopupView
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import java.sql.Date
import java.text.SimpleDateFormat
import java.util.*

/**
 * 计划拜访
 */
class PlanVisitActivity :
    BaseMvpActivity<PlanVisitActivity, PlanVisitPresenter, ActivityPlanVisitBinding>() {
    lateinit var loadPopup: LoadingPopupView
    private var pvTime: TimePickerView? = null
    private var dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
    private var dateType = ""
    private val getPlanRequest = GetPlanRequest()
    private val soapRequestBody = SoapRequestBody()
    private val soapEnvelop = SoapEnvelop()
    private var curPage = 1
    private val tempPlanBeanList = mutableListOf<PlanBean>()
    private val calendar = Calendar.getInstance()

    private val planListAdapter: PlanListAdapter by lazy {
        PlanListAdapter(this)
    }

    override fun getBinding(): ActivityPlanVisitBinding {
        return ActivityPlanVisitBinding.inflate(layoutInflater)
    }

    override fun getPresenter(): PlanVisitPresenter {
        return PlanVisitPresenter()
    }

    override fun initData() {
        calendar.time = Date()
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH))
        viewBinding.tvFrom.text = dateFormat.format(Date(calendar.timeInMillis))
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH))
        viewBinding.tvTo.text = dateFormat.format(Date(calendar.timeInMillis))

        getPlan()
    }


    override fun initView() {
        loadPopup = builder.asLoading("加载中...")
        viewBinding.clToolbar.setTitle(getString(R.string.choosePlan))
        viewBinding.clToolbar.clickListener = object : CustomerToolbar.ClickListener {
            override fun onBackListener() {
                finish()
            }

            override fun onRightListener() {
            }
        }


        viewBinding.list.rvList.adapter = planListAdapter

        planListAdapter.clickListener = object : BaseRecyclerAdapter.ClickListener {
            override fun clickListener(position: Int, view: View?) {
                val bundle = Bundle()
                val planBeanList = planListAdapter.planBeanList
                if (!planBeanList.isNullOrEmpty()) {
                    val planBean = planBeanList[position]
                    bundle.putParcelable("planBean", planBean)
                    startNextActivityForResult(
                        this@PlanVisitActivity,
                        ConstantsData.PLAN_REQUEST,
                        bundle,
                        PlanVisitDetailActivity::class.java
                    )
                }
            }

            override fun longClickListener(position: Int, view: View?): Boolean {
                return false
            }
        }

        //时间选择器
        pvTime = TimePickerBuilder(this) { date, _ ->
            when (dateType) {
                "1" -> {
                    viewBinding.tvFrom.text = dateFormat.format(date)
                }
                "2" -> {
                    viewBinding.tvTo.text = dateFormat.format(date)
                }
            }

        }
            .setType(booleanArrayOf(true, true, true, false, false, false))
            .build()

        viewBinding.tvFrom.setOnClickListener(this)
        viewBinding.tvTo.setOnClickListener(this)
        viewBinding.tvSearch.setOnClickListener(this)

        viewBinding.list.srlRefresh.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                curPage = 1
                getPlan()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                curPage += 1
                getPlan()
            }
        })

    }

    private fun getPlan() {
        if (curPage == 1) {
            tempPlanBeanList.clear()
        }
        getPlanRequest.curpage = "$curPage"
        getPlanRequest.qsrq = viewBinding.tvFrom.text.toString()
        getPlanRequest.zzrq = viewBinding.tvTo.text.toString()
        soapRequestBody.value = getPlanRequest
        soapEnvelop.body = soapRequestBody
        mPresenter?.getPlan(soapEnvelop)
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tvFrom -> {
                dateType = "1"
                pvTime?.show()
            }
            R.id.tvTo -> {
                dateType = "2"
                pvTime?.show()
            }
            R.id.tvSearch -> {
                curPage = 1
                getPlan()
            }
        }
    }

    fun showLoad() {
        if (!viewBinding.list.srlRefresh.isRefreshing && !viewBinding.list.srlRefresh.isLoading) {
            loadPopup.show()
        }
    }

    fun dismissLoad() {
        loadPopup.dismiss()
        if (viewBinding.list.srlRefresh.isRefreshing || viewBinding.list.srlRefresh.isLoading) {
            viewBinding.list.srlRefresh.finishRefresh()
            viewBinding.list.srlRefresh.finishLoadMore()
        }
    }

    fun setPlan(result: String) {
        val planBeanList = GsonUtil.fromJson<MutableList<PlanBean>>(
            result,
            object : TypeToken<MutableList<PlanBean>>() {}.type
        )

        if (planBeanList.isNullOrEmpty()) {
            viewBinding.list.srlRefresh.setEnableLoadMore(false)
            UiTools.showToast(R.string.noMoreInfo)
        } else {
            viewBinding.list.srlRefresh.setEnableLoadMore(true)
            tempPlanBeanList.addAll(planBeanList)
        }
        planListAdapter.planBeanList = tempPlanBeanList
        if (tempPlanBeanList.isNotEmpty()) {
            viewBinding.noData.clNoData.visibility = View.GONE
        } else {
            viewBinding.noData.clNoData.visibility = View.VISIBLE
        }
    }

}
